package NetWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 故我
 * Date: 2023-10-21
 * Time: 10:06
 */
public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIP,int serverPort) throws IOException {
        socket = new Socket(serverIP,serverPort);
    }

    public void Start() throws IOException {
        System.out.println("客户端启动!");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()) {
            //不断从标准输入框中获取数据并进行发送给客户端，接收数据并进行响应
            while(true){
                System.out.print("> ");
                String msgStr = scanner.next();
                if(msgStr.equals("exit")){
                    System.out.println("客户端退出了!");
                    break;
                }
                //构造成请求进行发送
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(msgStr);
                printWriter.flush();
                //获取响应
                Scanner scanner1 = new Scanner(inputStream);//从inputstream中读取数据
                String resp = scanner1.next();
                System.out.println(resp);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            socket.close();
        }
    }
    public static void main(String[] args) throws IOException {
        TcpEchoClient client= new TcpEchoClient("127.0.0.1",8080);
        client.Start();
    }
}
